package com.ppmall.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;


@Service
public class OssUtil {

    public String uploadFile(File file) {

        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tAbdKjvrr6wN6CGqnyv";
        String accessKeySecret = "QYpNz1e0IblitTPlwbETh3qMjPSU4m";
        String bucketName = "aaa-ppmall";

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String dirName = new DateTime().toString("yyyy/MM/dd");
        String fileName = dirName + "/" + uuid + file.getName().replace(" ", "_");

// 创建PutObjectRequest对象。
// 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file);

// 上传文件。
        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();

        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        return url;
    }
}
